import React, {Component} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  StatusBar,
  TextInput,
  TouchableOpacity,
  Image,
  Alert,
  ActivityIndicator,
  Dimensions,
  Linking
} from 'react-native';
import AreaSelect from '../components/AreaSelect';
import Picker from '../components/Picker';
import {
  showToast,
  checkMobile,
  isvalidPassword,
  isvalidInviteCode,
} from '../utils';
import Api from '../Api';
import MD5 from 'md5-es';
import {Actions} from 'react-native-router-flux';
const width = Dimensions.get('window').width;

export default class RegisterScreen extends Component {
  state = {
    name: '',
    account: '',
    phone: '',
    smsCode: '',
    country: '',
    province: '',
    city: '',
    county: '',
    count: 60,
    clickCode: false,
    password: '',
    passwordAgain: '',
    category: '',
    categorys: [
      {name: '网络', id: '网络'},
      {name: '系统', id: '系统'},
      {name: '弱电', id: '弱电'},
    ],
    inviteCode: '',
    checked: false,
  };
  handleSubmit = () => {
    if (!this.state.name) {
      showToast('请输入姓名');
      return;
    }
    // if (!this.state.account) {
    //   showToast('请输入账号');
    //   return;
    // }
    if (!this.state.phone) {
      showToast('请输入手机号');
      return;
    }
    if (!checkMobile(this.state.phone)) {
      showToast('手机号格式不正确');
      return;
    }
    if (!this.state.smsCode) {
      showToast('请输入验证码');
      return;
    }
    if (!this.state.password) {
      showToast('请输入密码');
      return;
    }
    if (!isvalidPassword(this.state.password)) {
      showToast('请输入8-16位，字母及数字组合的密码');
      return;
    }
    if (this.state.password !== this.state.passwordAgain) {
      showToast('两次输入密码不一致');
      return;
    }
    if (!this.state.country) {
      showToast('请选择国家');
      return;
    }
    if (!this.state.province || !this.state.city || !this.state.country) {
      showToast('请选择省市区');
      return;
    }
    if (!this.state.category) {
      showToast('请选择类别');
      return;
    }
    if (!this.state.inviteCode) {
      Alert.alert('提示', '您未输入邀请码，确认以个人身份注册吗？', [
        {
          text: '取消',
          style: 'cancel',
        },
        {text: '确定', onPress: this.handleRegisterCalback},
      ]);
    } else {
      if (!isvalidInviteCode(this.state.inviteCode)) {
        showToast('邀请码为8位，数字、大小写字母组合');
        return;
      }
      Api.byInviteCode(this.state.inviteCode).then(res => {
        if (!res.id) return;
        Alert.alert(
          '提示',
          `您输入的邀请码对应企业为${res.seproName}，您确认加入吗？`,
          [
            {
              text: '取消',
              style: 'cancel',
            },
            {text: '确定', onPress: this.handleRegisterCalback},
          ],
        );
      });
    }
  };
  handleRegisterCalback = () => {
    this.setState({
      loading: true,
    });
    Api.register({
      personName: this.state.name,
      //   account: this.state.account,
      phone: this.state.phone,
      personPassword: MD5.hash(this.state.password),
      inviteCode: this.state.inviteCode,
      captcha: this.state.smsCode,
      major: this.state.category,
      country: this.state.country,
      province: this.state.province,
      city: this.state.city,
      county: this.state.county,
    })
      .then(res => {
        showToast('注册成功');
        this.setState({
          loading: false,
        });
        setTimeout(() => {
          Actions.pop();
        }, 500);
      })
      .catch(_ => {
        this.setState({
          loading: false,
        });
      });
  };
  handleSelectArea = ({name, pickType, id}) => {
    this.setState({
      [pickType]: name,
    });
    // 切换国家，清空省市区
    switch (pickType) {
      case 'country':
        if (name !== this.state.country) {
          this.refs.provinceSelect.clear();
          this.refs.citySelect.clear();
          this.refs.countySelect.clear();
          this.setState({
            province: '',
            city: '',
            county: '',
          });
          this.refs.provinceSelect.pid = id;
        }
        break;
      case 'province':
        if (name !== this.state.province) {
          this.refs.citySelect.clear();
          this.refs.countySelect.clear();
          this.setState({
            city: '',
            county: '',
          });
          this.refs.citySelect.pid = id;
        }
        break;
      case 'city':
        if (name !== this.state.city) {
          this.refs.countySelect.clear();
          this.setState({
            county: '',
          });
          this.refs.countySelect.pid = id;
        }
        break;
    }
  };
  handleGetCode = () => {
    const {phone, clickCode} = this.state;
    if (clickCode) return;
    if (!phone) {
      showToast('请输入手机号');
      return;
    }
    if (!checkMobile(phone)) {
      showToast('手机号格式不正确');
      return;
    }
    this.setState({
      clickCode: true,
      count: 60,
    });

    Api.getCaptcha(phone).then(res => {
      console.log(res);
      if (res.status === 200) {
        clearInterval(this.timer);
        this.startTime = new Date().getTime();
        this.timer = setInterval(() => {
          let countDownTime = Math.round(
            60 - (new Date().getTime() - this.startTime) / 1000,
          );
          if (countDownTime <= 0) {
            this.setState({
              clickCode: false,
              count: 60,
            });
            clearInterval(this.timer);
          } else {
            this.setState({
              count: countDownTime,
            });
          }
        }, 1000);
      } else {
        this.setState({
          clickCode: false,
          count: 60,
        });
        clearInterval(this.timer);
      }
    });
  };
  handleChooseCategory = () => {
    this.refs.picker.showModal();
  };
  handleChooseCategoryCallback = value => {
    this.setState({
      category: value.name,
    });
  };
  render() {
    const {
      loading,
      checked,
      clickCode,
      count,
      category,
      categorys,
      name,
      account,
      phone,
      smsCode,
      password,
      passwordAgain,
    } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        <StatusBar barStyle="light-content" backgroundColor="#5096fc" />
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>姓名</Text>
          </View>
          <TextInput
            placeholder="请输入姓名"
            style={styles.ipt}
            onChangeText={value => this.setState({name: value})}
          />
        </View>
        {/* <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>账号</Text>
          </View>
          <TextInput
            placeholder="请输入账号"
            style={styles.ipt}
            onChangeText={value => this.setState({account: value})}
          />
        </View> */}
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>手机号</Text>
          </View>
          <TextInput
            placeholder="请输入手机号"
            style={styles.ipt}
            keyboardType="numeric"
            maxLength={11}
            onChangeText={value => this.setState({phone: value})}
          />
        </View>
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>验证码</Text>
          </View>
          <TextInput
            placeholder="请输入验证码"
            style={styles.ipt}
            keyboardType="numeric"
            maxLength={11}
            onChangeText={value => this.setState({smsCode: value})}
          />
          <TouchableOpacity
            style={styles.smsCode}
            activeOpacity={clickCode ? 1 : 0.2}
            onPress={this.handleGetCode}>
            <Text style={{color: clickCode ? '#ccc' : '#5196FD'}}>
              {clickCode ? count : '发送验证码'}
            </Text>
          </TouchableOpacity>
        </View>
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>密码</Text>
          </View>
          <TextInput
            secureTextEntry
            placeholder="请输入密码"
            style={styles.ipt}
            onChangeText={value => this.setState({password: value})}
          />
        </View>
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>确认密码</Text>
          </View>
          <TextInput
            secureTextEntry
            placeholder="请再次输入密码"
            style={styles.ipt}
            onChangeText={value => this.setState({passwordAgain: value})}
          />
        </View>
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>地区</Text>
          </View>
          <View style={styles.area}>
            <AreaSelect
              pickType="country"
              prefix=""
              extraStyle={styles.picker}
              onChange={this.handleSelectArea}
            />
            <AreaSelect
              pickType="province"
              prefix=""
              extraStyle={styles.picker}
              ref="provinceSelect"
              onChange={this.handleSelectArea}
            />
            <AreaSelect
              pickType="city"
              prefix=""
              extraStyle={styles.picker}
              ref="citySelect"
              onChange={this.handleSelectArea}
            />
            <AreaSelect
              pickType="county"
              prefix=""
              extraStyle={styles.picker}
              ref="countySelect"
              onChange={this.handleSelectArea}
            />
          </View>
        </View>
        <TouchableOpacity
          style={styles.commonItem}
          onPress={this.handleChooseCategory}>
          <View style={styles.label}>
            <Text style={styles.labelText}>类别</Text>
          </View>
          <View style={styles.ipt}>
            <Text style={{color: category ? '#000' : '#C7C7CD', fontSize: 15}}>
              {category || '请选择类别'}
            </Text>
          </View>
          <Image
            source={require('../assets/arrow_right.png')}
            style={styles.arrow}
          />
        </TouchableOpacity>
        <View style={styles.commonItem}>
          <View style={styles.label}>
            <Text style={styles.labelText}>邀请码</Text>
          </View>
          <TextInput
            placeholder="请输入邀请码"
            style={styles.ipt}
            maxLength={8}
            onChangeText={value => this.setState({inviteCode: value})}
          />
        </View>
        <TouchableOpacity
          disabled={!checked}
          onPress={this.handleSubmit}
          style={[
            styles.buttonStyle,
            !checked && styles.disableButtonStyle,
            loading && styles.disableButtonStyle,
          ]}>
          {loading ? (
            <ActivityIndicator
              style={{marginRight: 5}}
              color="#fff"
              size="small"
            />
          ) : null}
          <Text style={styles.buttonTextStyle}>注册</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={styles.agreeWrap}
          onPress={() => this.setState({checked: !checked})}>
          {!checked ? (
            <Image
              source={require('../assets/login_uncheckedex.png')}
              style={styles.unCheckIcon}
            />
          ) : (
            <Image
              source={require('../assets/login_checked.png')}
              style={styles.checkIcon}
            />
          )}
          <Text style={styles.agreeText}>阅读并同意隐私政策</Text>
          <Text
            style={styles.agreementText}
            onPress={() =>
              Linking.openURL('https://www.shyuezheng.com/download/policy.html')
            }>
            《隐私政策》
          </Text>
        </TouchableOpacity>
        <Picker
          ref="picker"
          options={categorys}
          onChange={this.handleChooseCategoryCallback}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    marginTop: 15,
  },
  style: {
    color: '#333',
  },
  commonItem: {
    flexDirection: 'row',
    alignItems: 'center',
    height: 40,
    borderBottomColor: 'rgba(151, 151, 151, 0.2)',
    borderBottomWidth: 0.5,
    marginHorizontal: 15,
  },
  label: {
    width: 80,
  },
  labelText: {
    fontSize: 15,
    color: '#000',
  },
  ipt: {
    flex: 1,
    color: '#000',
    fontSize: 15,
  },
  arrow: {
    width: 15,
    height: 15,
    marginLeft: 10,
  },
  area: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  picker: {
    height: 30,
    width: (width - 15 * 2 - 80) / 4,
  },
  buttonStyle: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: 40,
    backgroundColor: '#5196FD',
    borderRadius: 4,
    marginTop: 26,
    marginHorizontal: 15,
  },
  disableButtonStyle: {
    opacity: 0.5,
  },
  buttonTextStyle: {
    color: '#fff',
    fontSize: 15,
  },
  agreeWrap: {
    flexDirection: 'row',
    marginTop: 15,
    marginLeft: 15
  },
  unCheckIcon: {
    width: 12,
    height: 12,
    marginRight: 10
  },
  checkIcon: {
    width: 12,
    height: 12,
    marginRight: 10,
  },
  agreeText: {
    fontSize: 12,
    color: '#000',
  },
  agreementText: {
    color: '#5196FD',
    fontSize: 12,
    marginLeft: 5,
    textDecorationLine: 'underline',
    textDecorationColor: '#5196FD',
  },
  smsCode: {
    borderLeftColor: 'rgba(151, 151, 151, 0.2)',
    borderLeftWidth: 1,
    paddingLeft: 5,
    width: 80,
    flexDirection: 'row',
    justifyContent: 'center',
  },
});
